from django.shortcuts import render, HttpResponse, redirect, reverse
from django.views import View
from django.contrib import auth
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User


# Create your views here.

def login(request):
    return render(request, "login.html")


class Login(View):
    def get(self, request):
        return render(request, "login.html")

    def post(self, request):
        user = request.POST.get("username")
        pwd = request.POST.get("pwd")
        res = auth.authenticate(request, username=user, password=pwd)
        if res:
            auth.login(request, res)
            return HttpResponse("ok")
        return HttpResponse("登陆失败")


def test_user(request):
    # request.session.flush()
    user = request.user
    print(user.username, user.is_authenticated)
    return HttpResponse("ok")


def logout(request):
    auth.logout(request)
    return redirect(reverse("login"))


# def login_required(function=None, redirect_field_name=REDIRECT_FIELD_NAME, login_url=None):
@login_required(login_url="/login/")
def buy(request):
    return HttpResponse("购物")


def te(request):
    return HttpResponse("hello te")


def create_user(request):
    res = User.objects.create_user(username="xiong2", password="123")
    return HttpResponse(res)


def check_user(request):
    res = request.user.check_password("123456")
    # res = User.check_password("123")
    return HttpResponse(res)


def set_pass(request):
    res = request.user.set_password("123")
    request.user.save()
    return HttpResponse(res)